//
//  MemorandumListViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2018/1/16.
//  Copyright © 2018年 史宵宵. All rights reserved.
//

#import "MemorandumListViewController.h"
#import "AddMemorandumViewController.h"
#import "MemorandumInfo.h"
#import "MyDiaryInfo.h"
#import "SendFriendCircleViewController.h"
#import "PhotoBrowseViewController.h"
#import "MyEvaluationViewController.h"

@interface MemorandumListViewController ()
@property (nonatomic,strong) NSMutableArray *dataArray;
@end

@implementation MemorandumListViewController
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray=[NSMutableArray array];
    }
    return _dataArray;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    //    [Global setStatusBarBackgroundColor:[UIColor clearColor]];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    NSString *rightStr;
    if (self.memorandumListType == KMoodDiaryListType) {
        self.title = @"心情日志";
        rightStr = @"写日志";
    }else if (self.memorandumListType == KFutureMyselfListType) {
        self.title = @"未来畅想";
        rightStr = @"写畅想";
    }else if (self.memorandumListType == KTermGoalsListType) {
        self.title = @"学期目标";
        rightStr = @"";
    }else if (self.memorandumListType == KMyEvaluationType){
        self.title = @"我的自评";
        rightStr = @"";
    }else{
        self.title = @"备忘录";
        rightStr = @"新增";
    }
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightBarButtonItemWithTitle:rightStr target:self selector:@selector(addMemorandum)];
    [self setupRefresh];
}
#pragma mark - 新增备忘录
- (void)addMemorandum{
    if (self.memorandumListType == KTermGoalsListType) {
        
    }else if (self.memorandumListType != KMemorandumListType) {
        SendFriendCircleViewController *sendFriendCircleVC = [[ SendFriendCircleViewController alloc]init];
        __weak typeof(self) unself = self;
        sendFriendCircleVC.sendFriendCircleBlock = ^{
            [unself creatDataList];
        };
        if (self.memorandumListType == KMoodDiaryListType){
            sendFriendCircleVC.sendType = KSendMoodDiary;
            sendFriendCircleVC.titleStr = @"心情日记";
        }else if (self.memorandumListType == KFutureMyselfListType){
            sendFriendCircleVC.sendType = KSendFutureMyself;
            sendFriendCircleVC.titleStr = @"未来畅想";
        }else if (self.memorandumListType == KMoodDiaryListType){
            sendFriendCircleVC.sendType = KSendTermGoals;
            sendFriendCircleVC.titleStr = @"学期目标";
        }
        [self.navigationController pushViewController:sendFriendCircleVC animated:YES];
    }else{
        AddMemorandumViewController *addMemorandumVC = [[AddMemorandumViewController alloc]init];
        __weak typeof(self) unself = self;
        addMemorandumVC.sendMemorandumBlock = ^{
            [unself setupRefresh];
        };
        [self.navigationController pushViewController:addMemorandumVC animated:YES];
    }
 
}
- (void)creatDataList{
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    NSString *url ;
    if (self.memorandumListType == KMoodDiaryListType) {
        [dic setValue:@"2" forKey:@"topic_type"]; //2心情日志 3 未来畅想 4作业列表 6学期目标
        url = [JSPathUtil urlAppFriendGetDiaryList];
    }else if (self.memorandumListType == KFutureMyselfListType) {
        [dic setValue:@"3" forKey:@"topic_type"]; //2心情日志 3 未来畅想 4作业列表 6学期目标
        url = [JSPathUtil urlAppFriendGetDiaryList];
    }else if (self.memorandumListType == KTermGoalsListType) {
        url = [JSPathUtil urlAppSummaryGetTermGoalList];
    }else if (self.memorandumListType == KMyEvaluationType){
        url = [JSPathUtil urInterestGetEvaluateDateList];
    }else{
        url = [JSPathUtil urlAppInterestGetMemoryList];
    }
    
    [yjNetWorkManger requestType:POST andURL:url andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            if (self.pageNo == 1) {
                [self.dataArray removeAllObjects];
            }
            if (self.memorandumListType == KMyEvaluationType){
                [self.dataArray addObjectsFromArray:response];
                [self refreshCount:self.dataArray.count noDataText:@"还没有数据" totalRow:@"10"];
            }else if (self.memorandumListType != KMemorandumListType && self.memorandumListType != KTermGoalsListType) {
                [self.dataArray addObjectsFromArray:[MyDiaryInfo mj_objectArrayWithKeyValuesArray:response[@"list"]]];
                [self refreshCount:self.dataArray.count noDataText:@"还没有数据" totalRow:response[@"totalRow"]];
            }else{
                [MemorandumInfo mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
                    return @{@"memorandumId" : @"id"};
                }];
                
                [self.dataArray addObjectsFromArray:[MemorandumInfo mj_objectArrayWithKeyValuesArray:self.memorandumListType == KTermGoalsListType ? response:response[@"list"]]];
                
                [self refreshCount:self.dataArray.count noDataText:self.memorandumListType == KMemorandumListType ?@"还没有备忘录":@"还没有学期目标列表" totalRow:self.memorandumListType == KMemorandumListType ?response[@"totalRow"]:@""];
            }
            
            [self.tableView reloadData];
        }
    }];
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.memorandumListType == KMyEvaluationType){
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.userInteractionEnabled = YES;
        }
        cell.textLabel.text = self.dataArray[indexPath.row];
        return cell;
    }else if (self.memorandumListType != KMemorandumListType  && self.memorandumListType != KTermGoalsListType) {
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.userInteractionEnabled = YES;
            
            UILabel *label = [[UILabel  alloc]init];
            label.tag = 1000;
            label.font = [UIFont systemFontOfSize:14];
            label.numberOfLines = 0;
            [cell.contentView addSubview:label];
            
            UIImageView *commentImageView=[[UIImageView alloc]initWithFrame:CGRectMake( kScreenW - 20 - 25, 12, 20, 20)];
            commentImageView.tag = 1001;
            commentImageView.contentMode=UIViewContentModeScaleAspectFit;
            commentImageView.userInteractionEnabled = YES;
//            [commentImageView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickImage:)]];
            [cell.contentView addSubview:commentImageView];
        }
        MyDiaryInfo *myDiaryInfo = self.dataArray[indexPath.row];
        NSString *titleStr = strIsEmpty(myDiaryInfo.topic_context) ?@"":myDiaryInfo.topic_context ;//context
        NSArray *imageArray = [NSArray arrayWithArray:myDiaryInfo.image_list];//image_list
        
        UILabel *label = [cell.contentView viewWithTag:1000];
        label.text = titleStr;
        label.frame = CGRectMake(10, 10, kScreenW - 20, [Global getSizeOfString:titleStr maxWidth:kScreenW - 20 maxHeight:CGFLOAT_MAX withFontSize:14.6].height + 10) ;
        
        UIImageView *commentImageView = [cell.contentView viewWithTag:1001];
        
        if (!imageArray.count || strIsEmpty(imageArray[0])) {
            commentImageView.frame=CGRectZero;
            [self removeallSubViews:commentImageView];
        }
        else
        {
            [self removeallSubViews:commentImageView];
            commentImageView.frame= CGRectMake(10, CGRectGetMaxY(label.frame), kScreenW - 20, imageArray.count? (imageArray.count / 3+1)*( kScreenW-60)/3.0 : 0);
            for (int i=0; i < imageArray.count; i++) {
                UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake((( kScreenW-60)/3.0 + 15) * (i%3), (( kScreenW-60)/3.0 + 15) * (i / 3), ( kScreenW-60)/3.0, ( kScreenW-60)/3.0)];
                [imageView sd_setImageWithURL:[NSURL URLWithString:imageArray[i]] placeholderImage:KSIDEDEFAULTHEAD];
                imageView.backgroundColor= [UIColor clearColor];
                imageView.contentMode=UIViewContentModeScaleToFill;
                imageView.userInteractionEnabled = YES;
                imageView.tag=100*indexPath.row +i;
                [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickImage:)]];
                [commentImageView addSubview:imageView];
            }
        }
        return cell;
    }
    
    static NSString *CellIdentifier = @"memoCell";
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleValue1
                                      reuseIdentifier: CellIdentifier];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
     MemorandumInfo *memorandumInfo = self.dataArray[indexPath.row];
    
    if ( self.memorandumListType == KTermGoalsListType) {
        cell.textLabel.text = memorandumInfo.title;
    }else{
        cell.textLabel.text = memorandumInfo.content;
        cell.detailTextLabel.text = [memorandumInfo.add_time substringToIndex:10];
    }
   
    return cell;
}
- (void)clickImage:(UITapGestureRecognizer *)sender{
    MyDiaryInfo *myDiaryInfo = self.dataArray[sender.view.tag/100];
    NSArray *imageList = myDiaryInfo.image_list;
    NSMutableArray *imageArray = [[NSMutableArray alloc]init];
    [imageList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *imgUrl = [obj stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [imageArray addObject:imgUrl];
    }];
    PhotoBrowseViewController *photo = [[PhotoBrowseViewController alloc] initWithimageArray:[[NSMutableArray alloc]initWithArray:imageArray] withIndex:sender.view.tag%100 withType:0];
    photo.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:photo];
    [self presentViewController:nc animated:YES completion:nil];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.memorandumListType != KMemorandumListType && self.memorandumListType != KTermGoalsListType && self.memorandumListType != KMyEvaluationType) {
        MyDiaryInfo *myDiaryInfo = self.dataArray[indexPath.row];
        NSString *titleStr = strIsEmpty(myDiaryInfo.topic_context) ?@"":myDiaryInfo.topic_context ;//context
        NSArray *imageArray = [NSArray arrayWithArray:myDiaryInfo.image_list];//image_list

        double titleHeight = [Global getSizeOfString:titleStr maxWidth:kScreenW - 20 maxHeight:CGFLOAT_MAX withFontSize:14.6].height + 20;
        double imageHeight = imageArray.count? ((imageArray.count -1) / 3 + 1)*(( kScreenW-60)/3.0 + 10 ): 0;
        
        return titleHeight + imageHeight + 20;
    }
    return 44;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.memorandumListType == KTermGoalsListType) {
        SendFriendCircleViewController *sendFriendCircleVC = [[ SendFriendCircleViewController alloc]init];
        __weak typeof(self) unself = self;
        sendFriendCircleVC.sendFriendCircleBlock = ^{
            [unself creatDataList];
        };
        sendFriendCircleVC.sendType = KSendTermGoals;
        sendFriendCircleVC.titleStr = @"学期目标";
        MemorandumInfo *memorandumInfo = self.dataArray[indexPath.row];
        sendFriendCircleVC.friendCircleId = memorandumInfo.title;
        sendFriendCircleVC.sureContentStr = memorandumInfo.context;
        [self.navigationController pushViewController:sendFriendCircleVC animated:YES];
    }if (self.memorandumListType == KMyEvaluationType){
        MyEvaluationViewController *myEvaluationVC = [[MyEvaluationViewController alloc]init];
        myEvaluationVC.date = self.dataArray[indexPath.row];
        [self.navigationController pushViewController:myEvaluationVC animated:YES];
    }else if (self.memorandumListType != KMemorandumListType) {
    }else{
        AddMemorandumViewController *addMemorandumVC = [[AddMemorandumViewController alloc]init];
        addMemorandumVC.memorandumInfo = self.dataArray[indexPath.row];
        __weak typeof(self) unself = self;
        addMemorandumVC.sendMemorandumBlock = ^{
            [unself setupRefresh];
        };
        [self.navigationController pushViewController:addMemorandumVC animated:YES];
    }
    
}
/**
 *  移除视图
 *
 *  @param supView 父视图
 */
- (void )removeallSubViews:(UIView *)supView{
    for (id obj in supView.subviews) {
        [obj removeFromSuperview];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
